/*
 * Copyright (c) 2022, OUXIAOLONG. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.examples.springboot.jpa;

import java.util.Properties;

import javax.sql.DataSource;

import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
//@org.springframework.context.annotation.PropertySource("classpath:application.properties")
@EnableJpaRepositories("com.examples.springboot.jpa.repository")
@Import(HibernateJpaAutoConfiguration.class)
public class HibernateJpaConfiguration {

	@Autowired
	private DataSourceConfiguration datasource;

  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactory(Environment env) {
      final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
      em.setPackagesToScan(env.getProperty("basePackages",getClass().getPackage().getName()));
      em.setDataSource(myDataSource());
      em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
      em.setJpaProperties(getHibernateJpaProperties(env));
      return em;
  }

  @Bean
  public PlatformTransactionManager transactionManager(Environment env) {
      final JpaTransactionManager transactionManager = new JpaTransactionManager();
      transactionManager.setEntityManagerFactory(entityManagerFactory(env).getObject());

      return transactionManager;
  }

  @Bean
  public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
      return new PersistenceExceptionTranslationPostProcessor();
  }

  @Bean
  @Primary
  public static JpaProperties properties(Environment env) {
    final JpaProperties jpaProperties = new JpaProperties();
    jpaProperties.setShowSql(env.getProperty("jpa.show-sql", Boolean.class));

	if (env.containsProperty("jpa.database"))
		jpaProperties.setDatabase(Database.valueOf(env.getProperty("jpa.database")));
	if (env.containsProperty("jpa.platform"))
    jpaProperties.setDatabasePlatform(env.getProperty("jpa.platform"));
    return jpaProperties;
  }
  
  @Bean
  public ModelMapper modelMapper() {
      return new ModelMapper();
  }

  @Bean
  public DataSource myDataSource() {
	  return DataSourceBuilder.create().driverClassName(datasource.getDriverClassName()).url(datasource.getJdbcUrl()).username(datasource.getUsername()).password(datasource.getPassword()).build();
  }

  private Properties getHibernateJpaProperties(Environment env) {
    final Properties props = new Properties();
    props.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto","update"));
    props.setProperty("hibernate.dialect",      env.getRequiredProperty("hibernate.dialect"));
    props.setProperty("hibernate.show_sql",   env.getProperty("hibernate.show_sql","false"));
    props.setProperty("hibernate.format_sql", env.getProperty("hibernate.format_sql","false"));
    props.setProperty("hibernate.ejb.naming_strategy", env.getProperty("hibernate.ejb.naming_strategy","org.hibernate.cfg.ImprovedNamingStrategy"));
    props.setProperty("hibernate.enable_lazy_load_no_trans", env.getProperty("hibernate.enable_lazy_load_no_trans","false"));
    return props;
  }
}
